
package servlet;

import interfaceDAO.IDAOStation;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import algo.Algo;
import dao.DAOFactory;
import domain.Station;

public class ChoisirItineraire extends HttpServlet {

    public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
    	
    	
    	String strgLatDepart= request.getParameter( "latDepart" );
    	String strgLngDepart= request.getParameter( "lngDepart" );
    	String strgLatArrive= request.getParameter( "latArrivee" );
    	String strgLngArrive= request.getParameter( "lngArrivee" );
    	
    	System.out.println("I am at :"+strgLatDepart +";"+strgLngDepart );
    	System.out.println("Want to go to :"+strgLatArrive +";"+strgLngArrive );
    	
    	IDAOStation requester = DAOFactory.getDAOStation();
    	List<Station> touteStation = requester.getAllStations();
    	
    	/*Nous transformons les coordonées en double pour pouvoir des operations dessus*/
    	double latDepart = Double.parseDouble(strgLatDepart);
    	double lngDepart = Double.parseDouble(strgLngDepart);
    	double latArrive = Double.parseDouble(strgLatArrive);
    	double lngArrive = Double.parseDouble(strgLngArrive);
    	
    	/*selection des gares de depart et d'arrivé*/
    	Station stationDepart;
    	Station stationArrivee;
    	stationDepart = Algo.stationPlusProche(touteStation,latDepart, lngDepart);
    	stationArrivee = Algo.stationPlusProche(touteStation,latArrive, lngArrive);
    	
    	/*recup le nom de la meth callback   voir JSONP crossdomain*/
    	String nomMethCallback = request.getParameter("callback");
    	String jsonStationDepart ="{\"name\":\""+stationDepart.getExternalName()+"\" , \"lat\":\""+stationDepart.getLatitude()+"\" , \"lng\":\""+stationDepart.getLongitude()+"\"}";
    	String jsonStationArrivee ="{\"name\":\""+stationArrivee.getExternalName()+"\" , \"lat\":\""+stationArrivee.getLatitude()+"\" , \"lng\":\""+stationArrivee.getLongitude()+"\"}";
    	String jsonRep = nomMethCallback+"( {\"station\" :["+jsonStationDepart+","+jsonStationArrivee+"]});";
    	System.out.println(jsonRep);
    	
    	/*On ecrit la réponse*/
    	PrintWriter pw = response.getWriter();
    	pw.println(jsonRep);
    	
    }
}
